package javawdw.security.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javawdw.security.dao.ResourceDao;
import javawdw.security.dao.RoleResourceDao;
import javawdw.security.entity.Resource;
import javawdw.security.spi.IList;
import javawdw.security.spi.IResult;
import javawdw.security.spi.IService;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sun.jersey.api.representation.Form;
import com.sun.jersey.spi.resource.Singleton;

@Singleton 
@Path("/resource")
@Produces(MediaType.APPLICATION_JSON)
public class ResourceRs extends IService {
	private static Logger logger = Logger.getLogger(ResourceRs.class);
	private ResourceDao resourceDao;
	private RoleResourceDao roleResourceDao;
	
	@POST
	@Transactional(propagation = Propagation.REQUIRED)
	public IList find(Form form) {
		String id = form.getFirst("id");
		Map<String, Object> properties = new HashMap<String, Object>();
		if (id != null) {
			properties.put("id", id);
		}
		List<Resource> list = resourceDao.find(properties);
		logger.debug("查询所有资源路径");
		return new IList(list);
	}
	
	@POST
	@Path("saveOrUpdate")
	@Transactional(propagation = Propagation.REQUIRED)
	public String saveOrUpdate(Resource resource) {
		try {
			resourceDao.saveOrUpdate(resource);
			return SUCCESS;
		} catch (Exception e) {
			return FAILURE;
		}
	}
	
	@POST
	@Path("delete")
	@Transactional(propagation = Propagation.REQUIRED)
	public IResult delete(String idsStr) {
		IResult iResult = new IResult();
		String[] ids = idsStr == null ? null : idsStr.split(",");
		if (ids != null && ids.length != 0) {
			for (String id: ids) {
				try {
					Resource resource = resourceDao.delete(id);
					this.roleResourceDao.deleteByResourceId(resource.getId());
					iResult.addSuccess();
				} catch (Exception e) {
					e.printStackTrace();
					iResult.addFailure();
				}
			}
		}
		return iResult;
	}

	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}

	public void setRoleResourceDao(RoleResourceDao roleResourceDao) {
		this.roleResourceDao = roleResourceDao;
	}
}
